import { Module } from 'vuex'
import api from '@/api/config'

interface DashboardState {
  stats: {
    totalUsers: number
    totalSimulations: number
    successCount: number
    failureCount: number
    registrationTrend: Array<{ _id: string; count: number }>
    deviceStats: Array<{ _id: string; count: number }>
  }
  gaitData: Array<{
    id: number
    task_id: number
    stride_length: number
    step_height: number
    time_interval: number
    point_count: number
    result: string
    created_at: string
  }>
}

const dashboard: Module<DashboardState, any> = {
  namespaced: true,
  
  state: {
    stats: {
      totalUsers: 0,
      totalSimulations: 0,
      successCount: 0,
      failureCount: 0,
      registrationTrend: [],
      deviceStats: []
    },
    gaitData: []
  },
  
  mutations: {
    SET_STATS(state, stats) {
      state.stats = stats
    },
    SET_GAIT_DATA(state, data) {
      state.gaitData = data
    }
  },
  
  actions: {
    async fetchStats({ commit }, { startDate, endDate } = {}) {
      try {
        const response = await api.get('/query_gait_data', {
          params: {
            startDate: startDate?.toISOString(),
            endDate: endDate?.toISOString()
          }
        })
        
        // 处理步态数据，转换为统计信息
        const gaitData = response.data
        const stats = {
          totalUsers: 1, // 当前用户
          totalSimulations: gaitData.length,
          successCount: gaitData.filter(item => item.result === '成功').length,
          failureCount: gaitData.filter(item => item.result === '失败').length,
          registrationTrend: [], // 需要后端提供
          deviceStats: [] // 需要后端提供
        }
        
        commit('SET_STATS', stats)
        commit('SET_GAIT_DATA', gaitData)
      } catch (error) {
        console.error('Error fetching stats:', error)
      }
    },
    
    async generateGait({ dispatch }, { taskId }) {
      try {
        await api.post('/generate_gait', { taskId })
        // 重新获取数据
        dispatch('fetchStats')
      } catch (error) {
        console.error('Error generating gait:', error)
        throw error
      }
    }
  }
}

export default dashboard 